/* eslint-disable no-undef */

let isInit = false

export function init(id) {
  if (!id) return
  if (typeof window === 'undefined') return
  window.dataLayer = window.dataLayer || []
  window.gtag = function gtag() {
    dataLayer.push(arguments)
  }
  gtag('js', new Date())
  gtag('config', id)
  // 动态创建js
  var hm = document.createElement('script')
  hm.src = `https://www.googletagmanager.com/gtag/js?id=${id}`
  var s = document.getElementsByTagName('script')[0]
  s.parentNode.insertBefore(hm, s)
  isInit = true
}

export function push() {
  if (!isInit) return
}

export function trackPageView() {
  if (typeof gtag === 'undefined') return
  gtag('event', 'page_view')
}

export function trackEvent(event, action, opt_label, opt_value) {
  if (typeof gtag === 'undefined') return
  ga('event', event, {
    category,
    action,
    opt_label,
    opt_value
  })
}

/* eslint-disable no-undef */
function statistics() {
  !(function(c, b, d, a) {
    c[a] || (c[a] = {})
    c[a].config = {
      pid: 'kn47a@cff90aafcca2e22',
      appType: 'web',
      imgUrl: 'https://arms-retcode.aliyuncs.com/r.png?',
      enableSPA: true,
      useFmp: true
    }
    ;('Extended Mode')
    const s = b.createElement('script')
    b.body.insertBefore(s, b.body.firstChild)
    s.setAttribute('crossorigin', '')
    s.setAttribute('src', d)
    // with (b)
    //   with (body)
    //     with (insertBefore(createElement('script'), firstChild))
    //       setAttribute('crossorigin', '', (src = d))
  })(window, document, 'https://retcode.alicdn.com/retcode/bl.js', '__bl')
}

export default {
  init,
  trackPageView,
  trackEvent,
  statistics
}
